package com.account;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mybatis.mapper.UserDao;
import mybatis.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;

public class UpdateAccount extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        ------ 接收 ------
        int id = Integer.parseInt(req.getParameter("id"));
//        ------ 处理 ------
        Enumeration<String> params = req.getParameterNames();
        HashMap<String, Object> user = new HashMap<>();
        while (params.hasMoreElements()) {
            String name = params.nextElement();
            user.put(name, req.getParameter(name));
        }
        user.put("id", id);
        SqlSession session = MybatisUtils.getSqlSession();
        UserDao account = session.getMapper(UserDao.class);
        account.updateAccount(user);
        session.commit();
        session.close();
//        ------ 返回 ------
        HashMap<String, Object> ret = new HashMap<>();
        ret.put("code", 1);
        ret.put("message", "修改成功！");
        resp.setContentType("text/json; charset=utf-8");
        JSONObject content = new JSONObject(ret);
        PrintWriter writer = resp.getWriter();
        writer.println(content);
    }
}
